<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Admin\V1;


use App\Http\Controllers\ApiController;
use App\Http\Middleware\LocaleEnv;
use App\Http\Requests\Admin\V1\CouponTicket\CouponTicketDataRequest;
use App\Models\Coupon\CouponTicket;
use App\Services\Utils\TimeHelper;
use App\Services\Utils\Transaction;
use App\Services\Utils\Uuid;
use Illuminate\Http\Request;

class CouponTicketController extends ApiController
{
    const ROUTES = [
        'index'   => 'admin.v1.coupon-ticket.index',
        'store'   => 'admin.v1.coupon-ticket.store',
        'update'  => 'admin.v1.coupon-ticket.update',
        'destroy' => 'admin.v1.coupon-ticket.destroy',
    ];

    /**
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $coupon_tickets = (new CouponTicket)
            ->oldest('sort_order')
            ->paginate($request->per_page ?: 15);

        return $this->response(compact('coupon_tickets'));
    }

    /**
     *
     * @param CouponTicketDataRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(CouponTicketDataRequest $request)
    {
        $data = $this->assembleStoreData($request);

        $prob_sum = $this->sumExistTicketProbability();
            $this->checkCanOperate($data['probability'] + $prob_sum <= 1, 'probability sum less than 1');

        $coupon_ticket = (new CouponTicket)->create($data);

        return $this->response(compact('coupon_ticket'));
    }

    /**
     *
     * @param CouponTicketDataRequest $request
     *
     * @param $key
     *
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiAbstractException
     */
    public function update(CouponTicketDataRequest $request, $key)
    {
        $data = $this->assembleStoreData($request);

        $prob_sum = $this->sumExistTicketProbability($key);
            $this->checkCanOperate($data['probability'] + $prob_sum <= 1, 'probability sum less than 1');
        $coupon_ticket = (new CouponTicket)->find($key);
            $this->checkItemExist($coupon_ticket, 'coupon ticket');

        $updated = $coupon_ticket->update($data);

        return $this->response(compact('coupon_ticket', 'updated'));
    }

    /**
     *
     * @param $key
     *
     * @return array|\Illuminate\Http\Response
     */
    public function destroy($key)
    {
        $deleted = (new CouponTicket)->destroy($key);

        return $this->response(compact('deleted'));
    }

    /**
     * @param CouponTicketDataRequest $request
     *
     * @return array
     */
    private function assembleStoreData(CouponTicketDataRequest $request): array
    {
        $data = $request->only([
            'type', 'title', 'description', 'score', 'is_available',
            'started_at', 'ended_at', 'image', 'probability', 'sort_order', 'code',
        ]);


        // admin panel request timezone convert to UTC time
        $tz_offset = LocaleEnv::timezoneOffset();
        $data['started_at'] = TimeHelper::offsetMinutes($data['started_at'], $tz_offset);
        $data['ended_at'] = TimeHelper::offsetMinutes($data['ended_at'], $tz_offset);

        if (empty($data['code'])) {
            $data['code'] = Uuid::generate();
        }

        return $data;
    }

    /**
     * @param int|null $key
     *
     * @return float
     */
    private function sumExistTicketProbability(int $key = null): float
    {
        return (new CouponTicket)
            ->where('is_available', CouponTicket::IS_AVAILABLE)
            ->whereKeyNot($key)
            ->sum('probability');
    }
}